from trac.core import *
from trac.Timeline import ITimelineEventProvider
from trac.util import Markup
from time import mktime
from feedparser import parse as feedparse

class FeedTrackerPlugin(Component):
    implements(ITimelineEventProvider)

    def __init__(self, *args, **kwargs):
        Component.__init__(self, *args, **kwargs)
        self.feeds = self._get_feeds()

    def _get_feeds(self):
        feeds = []
        i = 1
        while True:
            name = self.config.get('feeds', 'name%d' % i, None)
            url = self.config.get('feeds', 'url%d' % i, None)
            if name and url:
                feeds.append({'name' : name, 'url' : url})
                i = i + 1
            else:
                break
        return feeds

    # ITimelineEventProvider
    
    def get_timeline_filters(self, req):
        for feed in self.feeds:
            yield (feed['url'], feed['name'], True)

    def get_timeline_events(self, req, start, stop, filters):
        events = []
        for url in filters:
            feed = feedparse(url) # TODO : Cache
            for entry in feed.entries:
                entry_time = mktime(entry.updated_parsed)
                if ((entry_time >= start) and
                    (entry_time <= stop)):
                    try:
                        entry_author = entry.author
                    except:
                        entry_author = None
                    event = ('feeditem',
                             entry.link,
                             entry.title,
                             entry_time,
                             entry_author,
                             Markup(entry.summary))
                    events.append(event)
        return events
